package message

import (
	"aixinge/api/model/common/request"
	"aixinge/api/model/message"
	messageReq "aixinge/api/model/message/request"
	"aixinge/core/mail"
	"aixinge/global"
	"aixinge/utils"
	"aixinge/utils/snowflake"
	"errors"
)

type MailTemplateService struct {
}

func (e *MailTemplateService) Create(app message.MailTemplate) error {
	app.ID = utils.Id()
	// 状态，1、正常 2、禁用
	app.Status = 1
	return global.DB.Create(&app).Error
}

func (e *MailTemplateService) Delete(idsReq request.IdsReq) error {
	return global.DB.Delete(&[]message.MailTemplate{}, "id in ?", idsReq.Ids).Error
}

func (e *MailTemplateService) Update(mt message.MailTemplate) (error, message.MailTemplate) {
	return global.DB.Updates(&mt).Error, mt
}

func (e *MailTemplateService) GetById(id snowflake.ID) (err error, mt message.MailTemplate) {
	err = global.DB.Where("id = ?", id).First(&mt).Error
	return err, mt
}

func (e *MailTemplateService) Page(page request.PageInfo) (err error, list interface{}, total int64) {
	db := global.DB.Model(&message.MailTemplate{})
	var mtList []message.MailTemplate
	err = db.Count(&total).Error
	if total > 0 {
		err = db.Limit(page.PageSize).Offset(page.Offset()).Find(&mtList).Error
	}
	return err, mtList, total
}

// SendMail 发送邮件
func (e *MailTemplateService) SendMail(params messageReq.ApiParams, channelList []message.Channel) error {
	err, mt := e.GetById(params.TemplateId)
	if err != nil {
		return err
	}
	if &mt == nil {
		return errors.New("指定模板不存在")
	}

	replyToAddress := params.ContentString("replyToAddress")
	to, err := params.ContentStringSlice("to")
	if err != nil {
		return err
	}
	cc, err := params.ContentStringSlice("cc")
	if err != nil {
		return err
	}
	bcc, err := params.ContentStringSlice("bcc")
	if err != nil {
		return err
	}
	html := mt.Type == 2

	var context = params.GetContext()

	subject, err := params.Render(mt.Subject, context)
	if err != nil {
		return errors.New("指定模板主题渲染失败")
	}

	body, err := params.Render(mt.Content, context)
	if err != nil {
		return errors.New("指定模板内容渲染失败")
	}

	// 循环至渠道成功发送
	for _, channel := range channelList {
		identity := channel.ConfigString("identity")
		username := channel.ConfigString("username")
		password := channel.ConfigString("password")
		host := channel.ConfigString("host")
		port := channel.ConfigString("port")
		smtp := mail.NewSmtp(identity, username, password, host, port)
		err = smtp.SendMail(html, subject, body, replyToAddress, to, cc, bcc)
		if err == nil {
			break
		}
	}
	return err
}
